{{#error_message}}
    <div class="cash_error cash_{{element_type}}_error">
        {{error_message}}
    </div>
{{/error_message}}



<div class="cm-store cm-item item-{{item_id}}">
   <div class="cm-store cm-inner">
      {{#item_image_url}}<img src="{{item_image_url}}" alt="" />{{/item_image_url}}
      <h2>{{item_name}}</h2>
      <span class="cm-itemprice">{{currency}}{{item_price}}{{#item_flexible_price}} {{copy_flexibleprice_suffix}}{{/item_flexible_price}}</span>
      <div class="cm-description">{{{item_description}}}</div>
      {{#is_available}}
      {{#attributes}}<select class="cm-attribute" name="{{name}}" data-key="{{key}}" data-itemid="{{item_id}}" data-totalattributes="{{attributes_count}}" data-attributeorder="{{index}}"><option value="resetattributes" {{#defaultcountermenu}}data-countermenu='{{defaultcountermenu}}'{{/defaultcountermenu}}>{{copy_choose_verb}} {{key}}</option>{{#items}}<option value="{{key}}" {{#countermenu}}data-countermenu='{{countermenu}}'{{/countermenu}}>{{key}}</option>{{/items}}</select>{{/attributes}}
      {{#item_flexible_price}}
      <span class="cm-store-flexible-price">
         <span class="cm-store-currency">{{currency}}</span>
         <input type="text" name="total_price" data-itemid="{{item_id}}" data-totalattributes="{{attributes_count}}" data-atleast="{{item_price}}" class="cm-price" value="{{item_price}}" />
      </span>
      {{/item_flexible_price}}
      <button type="button" data-itemid="{{item_id}}" data-price="{{item_price}}" class="button cm-buynow cm-item-{{item_id}}"{{#has_variants}} disabled="disabled"{{/has_variants}}>{{#has_variants}}{{copy_choose_variants}}{{/has_variants}}{{^has_variants}}<span class="cm-price">{{currency}}{{item_price}}</span> - {{copy_buy}}{{/has_variants}}</button>
      {{/is_available}}
      {{^is_available}}
         <span class="cm-unavailable">
            {{copy_unavailable}}
         </span>
      {{/is_available}}
   </div>
</div>



<script type="text/javascript">
(function() {
	'use strict';
	var cm = window.cashmusic;

   // get stripe public key
   {{#stripe_public_key}}
      var stripe_public_key = "{{stripe_public_key}}";
   {{/stripe_public_key}}
   {{^stripe_public_key}}
      var stripe_public_key = false;
   {{/stripe_public_key}}

   // we like paypal?
   {{#paypal_connection}}
      var paypal = true;
   {{/paypal_connection}}
   {{^paypal_connection}}
      var paypal = false;
   {{/paypal_connection}}

   // set shipping with regions, or to false if there is no shipping
   {{#no_shipping}}
      var shipping = false;
   {{/no_shipping}}
   {{^no_shipping}}
      var shipping = {
         "r1": "{{region1_name}} (${{region1_cost}})",
         "r2": "{{region2_name}} (${{region2_cost}})"
      };
   {{/no_shipping}}

   // go
	cm.events.add(cm,'ready', function(e) {
		cm.session.start();

		// sort all the cart buttons
		var button = document.querySelector('.cm-buynow.cm-item-{{item_id}}');
		if (button) {
			cm.events.add(button,'click', function(e) {
            e.preventDefault();

            var p = button.getAttribute('data-price');
            var submitUrl = window.location.href.split('/embed/')[0]+'/payload';
				var poststring = 'cash_request_type=commerce&cash_action=emptycart&element_id={{element_id}}';
            cm.ajax.send(submitUrl, poststring, function(r) {
               if (p > 0) {
   					var poststring = 'cash_request_type=commerce&cash_action=addtocart&element_id={{element_id}}&item_id=' + button.getAttribute('data-itemid') + '&price=' + p;
   					if (button.getAttribute('data-variantid')) {
   						poststring += '&item_variant='+ encodeURIComponent(button.getAttribute('data-variantid'));
   					}

   					cm.ajax.send(submitUrl, poststring, function(r) {
                     cm.checkout.begin({
                        "stripe": stripe_public_key,
                        "paypal": paypal,
                        "currency": "{{currency}}", // USD = auto default
                        "shipping": shipping
                    }); /*,
                     "total": "{{currency}}"+parseFloat(button.getAttribute('data-price')),*/
   					});
               } else {
                  cm.events.fire(cm,'checkoutdata',{
                     "origin":"",
                     "email":"",
                     "name":""
                  });
               }
            });
			});

         cm.events.add(cm, 'checkoutdata', function (payment) {
            var f = document.createElement('form');
            f.method = 'post';
            f.action = '';

            var els = ['cash_request_type','cash_action','element_id','shipping_price','total_price','shipping_info','paypal','stripe','origin','email_address','customer_name','geo','finalize_url'];
            for (var i = 0, len = els.length; i < len; i++) {
               var inp = document.createElement('input');
               inp.type = 'hidden';
               inp.name = els[i];
               inp.value = '';
               f.appendChild(inp);
            }

            f.cash_request_type.value = 'commerce';
            f.cash_action.value = 'initiatecheckout';
            {{#session_id}}f.session_id = '{{session_id}}';{{/session_id}}
            f.element_id.value = {{element_id}};
            f.total_price.value = parseFloat(button.getAttribute('data-price'));
            f.origin.value = payment.detail.origin;
            f.email_address.value = payment.detail.email;
            f.customer_name.value = payment.detail.name;
            f.geo.value = cm.geo;
            if (cm.embedded) {
   				if (cm.get['params']['location']) {
   					f.finalize_url.value = cm.get['params']['location'];
   				} else {
   					f.finalize_url.value = window.location.href;
   				}
   			} else {
   				f.finalize_url.value = top.location.href;
   			}
            if (payment.detail.paypal) {
               f.paypal.value = 1;
            }
            if (payment.detail.stripe) {
               f.stripe.value = payment.detail.stripe;
            }

            // add shipping to form
            if (payment.detail.shipping) {
               f.shipping_info.value = JSON.stringify(payment.detail.shipping);
               if (payment.detail.shipping['shipping-region']) {
                  var requesturl = '{{api_url}}/verbose/commerce/editcartshipping/element_id/{{element_id}}/region/' + payment.detail.shipping['shipping-region'] + '/';
                  requesturl += '?ts=' + new Date().getTime();
                  cm.ajax.send(requesturl, false,
                     function() {
                        initiatePayment(f);
                     }
                  );
               }
            } else {
               initiatePayment(f);
            }
         });

         cm.loadScript(cm.path + '/checkout/checkout.js', function () {
            cm.checkout.prep();
         });
		}

      function initiatePayment(f) {
         document.body.appendChild(f);
         cm.ajax.send(
				'{{public_url}}/request/payload',
				cm.ajax.encodeForm(f),
				function(details) {
					if (details.substring(0,4) == 'http') {
						top.location.href = details;
					} else if (details == 'success') {
                  cm.overlay.reveal({"element":"{{element_id}}","endpoint":"{{public_url}}","state":"success"});
               } else {
                  cm.overlay.reveal('There was a problem with your payment. Please try again.');
               }
				},
            function(details) {
               cm.overlay.reveal('There was a problem with your payment. Please try again.');
				}
			);
      }

		// keep prices correct
		var prices = document.querySelectorAll('input.cm-price');
		if (prices.length > 0) {
			for (var i = 0, len = prices.length; i < len; i++) {
				cm.events.add(prices[i],'keyup', function(e) {
					var newprice = parseFloat(this.value);
               // force 0.00 or 0.50 but nothing in between (for minimum price stuff)
               if (newprice > 0 && newprice < 0.5) {
                  newprice = 0.5;
               }

					if (newprice >= parseFloat(this.getAttribute('data-atleast'))) {
						var pricespan = document.querySelector('button.cm-buynow.cm-item-' + this.getAttribute('data-itemid') + ' span.cm-price');
						if (pricespan) {
							pricespan.innerHTML = '{{currency}}' + newprice.toFixed(2);
						}
						document.querySelector('button.cm-buynow.cm-item-' + this.getAttribute('data-itemid')).setAttribute('data-price',newprice.toFixed(2))
					}
					e.preventDefault();
					return false;
				});

				cm.events.add(prices[i],'blur', function(e) {
					this.value = document.querySelector('button.cm-buynow.cm-item-' + this.getAttribute('data-itemid')).getAttribute('data-price');
				});
			}
		}

		// item variants
		var attributes = document.querySelectorAll('select.cm-attribute');
		if (attributes.length > 0) {
			for (var i = 0, len = attributes.length; i < len; i++) {
				cm.events.add(attributes[i],'blur', function(e) {
					var b = document.querySelector('button.cm-buynow.cm-item-' + e.target.getAttribute('data-itemid'));

					if (e.target.getAttribute('data-totalattributes') > 1) {
						var allselects = e.target.parentNode.querySelectorAll('select');
						var otherselect = false;
						for (var ii = 0, l = allselects.length; ii < l; ii++) {
							if (allselects[ii] != e.target) {
								otherselect = allselects[ii];
								break;
							}
						}

						if (otherselect) {
							var supportedoptions = JSON.parse(e.target.options[e.target.selectedIndex].getAttribute('data-countermenu').replace('&apos;', '\''));
							var otheroptions = otherselect.querySelectorAll('option');
							for (var i = 0, len = otheroptions.length; i < len; i++) {
								otheroptions[i].setAttribute('disabled','disabled');
								if (otheroptions[i].value == 'resetattributes' || supportedoptions.indexOf(otheroptions[i].value) !== -1) {
									otheroptions[i].removeAttribute('disabled');
								}
							}
							if (e.target.value != 'resetattributes' && otherselect.value != 'resetattributes') {
								var attributekey = {};
								if (e.target.getAttribute('data-attributeorder') == 0) {
									attributekey[e.target.getAttribute('data-key').replace('&apos;', '\'')] = e.target.value.replace('&apos;', '\'');
									attributekey[otherselect.getAttribute('data-key').replace('&apos;', '\'')] = otherselect.value.replace('&apos;', '\'');
								} else {
									attributekey[otherselect.getAttribute('data-key').replace('&apos;', '\'')] = otherselect.value.replace('&apos;', '\'');
									attributekey[e.target.getAttribute('data-key').replace('&apos;', '\'')] = e.target.value.replace('&apos;', '\'');
								}
								attributekey = JSON.stringify(attributekey);
								b.setAttribute('data-variantid',attributekey);
								b.removeAttribute('disabled');
								b.innerHTML = '<span class="cm-price">{{currency}}'+b.getAttribute('data-price')+'</span> - {{copy_buy}}';
							} else {
								b.removeAttribute('data-variantid');
								b.setAttribute('disabled','disabled');
								b.innerHTML = '{{copy_choose_variants}}';
							}
						}
					} else {
						if (e.target.value != 'resetattributes') {
                     var attributekey = {};
                     attributekey[e.target.getAttribute('data-key').replace('&apos;', '\'')] = e.target.value.replace('&apos;', '\'');
                     attributekey = JSON.stringify(attributekey);
                     b.setAttribute('data-variantid',attributekey);
							b.removeAttribute('disabled');
							b.innerHTML = '<span class="cm-price">{{currency}}'+b.getAttribute('data-price')+'</span> - {{copy_buy}}';
						} else {
							b.removeAttribute('data-variantid');
							b.setAttribute('disabled','disabled');
							b.innerHTML = '{{copy_choose_variants}}';
						}
					}
				});
				cm.events.add(attributes[i],'change', function(e) {
					e.target.blur(); // using change to fire blur gives us change events consistently. ff doesn't do auto-blur, ios safari doesn't do change
				});
			}
		}

      {{#showsuccess}}
          cm.session.setid({"id":"{{session_id}}"});
          cm.overlay.reveal({"element":"{{element_id}}","endpoint":"{{public_url}}","state":"success"});
      {{/showsuccess}}
	});
}());
</script>
